package main

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"time"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type Alert struct {
	Receiver          string            `json:"receiver"`
	Status            string            `json:"status"`
	Alerts            []AlertItems      `json:"alerts"`
	GroupLabels       map[string]string `json:"groupLabels"`
	CommonLabels      map[string]string `json:"commonLabels"`
	CommonAnnotations map[string]string `json:"commonAnnotations"`
	ExternalURL       string            `json:"externalURL"`
	Version           string            `json:"version"`
	GroupKey          string            `json:"groupKey"`
	TruncatedAlerts   int               `json:"truncatedAlerts"`
}

type AlertItems struct {
	Status       string            `json:"status"`
	Labels       map[string]string `josn:"labels"`
	Annotations  map[string]string `json:"annotations"`
	StartsAt     string            `json:"startsAt"`
	EndsAt       string            `json:"endsAt"`
	GeneratorURL string            `json:"generatorURL"`
	Fingerprint  string            `json:"fingerprint"`
}

var alert Alert

func connectToMongo() (*mongo.Client, error) {
	// 连接到MongoDB
	client, err := mongo.NewClient(options.Client().ApplyURI("mongodb://192.168.100.30:27017"))
	if err != nil {
		return nil, err
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	err = client.Connect(ctx)
	if err != nil {
		return nil, err
	}

	return client, nil
}

func handlePostRequest(w http.ResponseWriter, r *http.Request) {
	client, err := connectToMongo()
	if err != nil {
		http.Error(w, "Failed to connect to database", http.StatusInternalServerError)
		return
	}
	defer client.Disconnect(context.Background())

	body, err := io.ReadAll(r.Body)
	json.Unmarshal(body, &alert)

	if err != nil {
		http.Error(w, "Failed to read request body", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	// 将body插入到MongoDB的 monitor 数据库的 alert 集合
	collection := client.Database("monitor").Collection("alert")
	_, err = collection.InsertOne(context.TODO(), alert)
	if err != nil {
		http.Error(w, "Failed to insert data into database", http.StatusInternalServerError)
		return
	}

	fmt.Println(string(body))
	fmt.Fprint(w, "POST request received and data inserted into MongoDB")
}

func main() {
	http.HandleFunc("/", handlePostRequest)
	http.ListenAndServe(":5001", nil)
}
